//
//  ForgetPasswordViewController.m
//  ChatDemo-UI2.0
//
//  Created by li.guibin on 15/12/2.
//  Copyright © 2015年 li.guibin. All rights reserved.
//

#import "ForgetPasswordViewController.h"

@interface ForgetPasswordViewController ()<UITextFieldDelegate,UIAlertViewDelegate>
@property (weak, nonatomic) IBOutlet UITextField *resetPhoneNum;
@property (weak, nonatomic) IBOutlet UITextField *resetCode;
@property (weak, nonatomic) IBOutlet UITextField *resetPassword;
@property (weak, nonatomic) IBOutlet UITextField *comfirmPassword;
@property (weak, nonatomic) IBOutlet UIButton *verificationBtn;
@property (weak, nonatomic) IBOutlet UIButton *resetBtn;
@end

@implementation ForgetPasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [backButton setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
    [backButton addTarget:self.navigationController action:@selector(popViewControllerAnimated:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    [self.navigationItem setLeftBarButtonItem:backItem];
    
    
    _comfirmPassword.layer.cornerRadius = 5.0f;
    _resetBtn.layer.cornerRadius = 5.0f;
    
    _resetPhoneNum.delegate=self;
    [_resetPhoneNum addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    _resetCode.delegate=self;
    [_resetCode addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    _resetPassword.delegate=self;
    [_resetPassword addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

    _comfirmPassword.delegate=self;
    [_comfirmPassword addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

    // Do any additional setup after loading the view.
}
- (IBAction)verify:(id)sender{
    if (_resetPhoneNum.text.length == 0) {
        [Utils alertViewWithMessage:@"填写手机号"];
        return;
    }
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"api_VerifyCode_get" forKey:@"method"];
    [dict setObject:@"1" forKey:@"type"];
    [dict setObject:_resetPhoneNum.text forKey:@"mobile"];
    [Utils get:nil parameters:dict success:^(NSInteger recode ,id jsonObject){
        NSLog(@"%@", jsonObject);
        /*启动计时器*/
        self->ti= [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
        self->time=60;
        
        self->_verificationBtn.enabled=NO;
        [self->_verificationBtn setBackgroundColor:[Utils stringToColor:@"dddddd"]];
        [self->_verificationBtn setTitleColor:[Utils stringToColor:@"979797"] forState:UIControlStateNormal];
        [self->_verificationBtn setTitle:[NSString stringWithFormat:@"等待%d秒",self->time] forState:UIControlStateNormal];
    } failure:^(NSInteger recode , NSError * error){
        
    }];
}
/**
 *  编辑人：张东海
 *  时间：2016年5月26日
 *  更改或添加内容：计时器调用方法
 *  备注：
 */

-(void)timerFireMethod:(NSTimer *)timer{
    
    time-=1;
    [self->_verificationBtn setTitle:[NSString stringWithFormat:@"等待%d秒",time] forState:UIControlStateNormal];
    // lab.text=[NSString stringWithFormat:@"等待%d秒",time];
    if (time==0) {
        self->_verificationBtn.enabled=YES;
        
        [self->_verificationBtn setBackgroundColor:[Utils stringToColor:@"fffbb5"]];
        [self->_verificationBtn setTitleColor:[Utils stringToColor:@"ae7d3d "] forState:UIControlStateNormal];
        [self->_verificationBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        if ([timer isValid] == YES) {
            [timer invalidate];
            timer = nil;
        }
        
        
    }
    
}

- (IBAction)resetPassword:(id)sendeer{
    if (_resetPhoneNum.text.length == 0 ||_resetCode.text.length == 0||[[_resetPassword.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0 ||[[_comfirmPassword.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0){
        
        [Utils alertViewWithMessage:@"请将信息填写完整"];
        return;
    }
    
    if (_resetPassword.text.length<6 ||_resetPassword.text.length>16) {
        [Utils alertViewWithMessage:@"请将密码限制在6-16位以内"];
        return;
    }
    
    if (_comfirmPassword.text.length<6 || _comfirmPassword.text.length>6) {
        
        [Utils alertViewWithMessage:@"请将确认密码限制在6-16位以内"];
        return;
    }
    if (![_resetPassword.text isEqualToString:_comfirmPassword.text]) {
        [Utils alertViewWithMessage:@"两次输入密码不一致"];
        return;
    }
    
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"api_user_repass" forKey:@"method"];
    [dict setObject:_resetCode.text forKey:@"verify"];
    [dict setObject:_resetPhoneNum.text forKey:@"mobile"];
    [dict setObject:[Utils MD5EncryptWith:_resetPassword.text] forKey:@"newpass"];
    
    
    [Utils get:nil parameters:dict success:^(NSInteger recode ,id jsonObject){
        
        
        NSDictionary * dict = (NSDictionary *)jsonObject;
        //[Utils alertViewWithMessage:[dict objectForKey:@"re_info"]];
        NSDictionary * personalImformation = [dict objectForKey:@"re_data"];
        //if (personalImformation.count>0) {
        
        BOOL save = [SyUserInfomation personalImformationSaveWtih:personalImformation];
        NSLog(@"save status 1 is success 0 is failture :%i",save);
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:[dict objectForKey:@"re_info"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
            
        //}
        
    } failure:^(NSInteger recode, NSError * error){
    }];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)textFieldDidChange:(UITextField *)textField
{
    if (textField == _resetPhoneNum) {
        if (textField.text.length > 11) {
            textField.text = [textField.text substringToIndex:11];
        }
    }else if (textField==_resetCode)
    {
        if (textField.text.length >6) {
            textField.text = [textField.text substringToIndex:6];
        }
        
    }else if (textField==_resetPassword)
    {
        if (_resetPassword.text.length > 16) {
            UITextRange *markedRange = [_resetPassword markedTextRange];
            if (markedRange) {
                return;
            }
            //Emoji占2个字符，如果是超出了半个Emoji，用15位置来截取会出现Emoji截为2半
            //超出最大长度的那个字符序列(Emoji算一个字符序列)的range
            NSRange range = [_resetPassword.text rangeOfComposedCharacterSequenceAtIndex:16];
            _resetPassword.text = [_resetPassword.text substringToIndex:range.location];
        }
        
    }else if (textField==_comfirmPassword)
    {
        if (_comfirmPassword.text.length > 16) {
            UITextRange *markedRange = [_comfirmPassword markedTextRange];
            if (markedRange) {
                return;
            }
            //Emoji占2个字符，如果是超出了半个Emoji，用15位置来截取会出现Emoji截为2半
            //超出最大长度的那个字符序列(Emoji算一个字符序列)的range
            NSRange range = [_comfirmPassword.text rangeOfComposedCharacterSequenceAtIndex:16];
            _comfirmPassword.text = [_comfirmPassword.text substringToIndex:range.location];
        }
        
    }

    
    
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.navigationController popViewControllerAnimated:YES];
    });
    
    
    //[self.navigationController popViewControllerAnimated:YES];
}

@end
